package com.zw.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zw.common.constant.ProductConstant;
import com.zw.common.entity.product.AttrAttrgroupRelationEntity;
import com.zw.common.entity.product.AttrEntity;
import com.zw.common.entity.product.AttrGroupEntity;
import com.zw.common.entity.product.CategoryEntity;
import com.zw.common.vo.product.SpuItemAttrGroupVO;
import com.zw.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.zw.gulimall.product.dao.AttrDao;
import com.zw.gulimall.product.dao.CategoryDao;
import com.zw.gulimall.product.service.AttrAttrgroupRelationService;
import com.zw.gulimall.product.service.AttrService;
import com.zw.gulimall.product.vo.AttrGroupRelationVo;
import com.zw.gulimall.product.vo.AttrGroupWithAttrRespVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zw.common.utils.PageUtils;
import com.zw.common.utils.Query;

import com.zw.gulimall.product.dao.AttrGroupDao;
import com.zw.gulimall.product.service.AttrGroupService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.w3c.dom.Attr;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrService attrService;

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrAttrgroupRelationService relationService;

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        LambdaQueryWrapper<AttrGroupEntity> wrapper = new LambdaQueryWrapper<AttrGroupEntity>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(item -> {
                item.like(AttrGroupEntity::getAttrGroupId, key)
                        .or().like(AttrGroupEntity::getAttrGroupName, key);
            });
        }
        if (catelogId != 0) {
            wrapper.eq(AttrGroupEntity::getCatelogId, catelogId);
        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<AttrEntity> queryAttrGroupRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = relationDao.selectList(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                .eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId));
        List<Long> collect = attrAttrgroupRelationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        List<AttrEntity> attrEntities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(collect)) {
            attrEntities = attrDao.selectList(new LambdaQueryWrapper<AttrEntity>()
                    .in(AttrEntity::getAttrId, collect));
        }
        return attrEntities;
    }

    /**
     * @Description: 获取属性分组里面还没有关联的本分类里面的其他基本属性，方便添加新的关联
     * @Author: ${USER}
     * @Date: 2023/7/12 11:25
     * @Param: [attrGroupId]
     * @Return: com.zw.common.utils.PageUtils
     **/
    @Override
    public PageUtils queryNoAttrGroupRelationPage(Map<String, Object> params, Long attrGroupId) {
//        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
//                .eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId));
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new LambdaQueryWrapper<>());
        AttrGroupEntity attrGroupEntity = baseMapper.selectById(attrGroupId);

        CategoryEntity categoryEntity = categoryDao.selectOne(new LambdaQueryWrapper<CategoryEntity>()
                .eq(CategoryEntity::getCatId, attrGroupEntity.getCatelogId()));

        List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());

        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<AttrEntity>()
                .eq(AttrEntity::getCatelogId, categoryEntity.getCatId())
                .eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (!CollectionUtils.isEmpty(attrIds)) {
            wrapper.notIn(AttrEntity::getAttrId, attrIds);
        }
        Object key = params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(item -> {
                item.like(AttrEntity::getAttrId, key)
                        .or().like(AttrEntity::getAttrName, key);
            });
        }
        IPage<AttrEntity> page = attrService.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void deleteRelation(List<AttrGroupRelationVo> vo) {
        List<AttrAttrgroupRelationEntity> entities = vo.stream().map(item -> {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relation);
            return relation;
        }).collect(Collectors.toList());
        baseMapper.deleteRelation(entities);
    }

    @Override
    public void saveAttrRelation(List<AttrGroupRelationVo> vos) {
        List<AttrAttrgroupRelationEntity> entities = vos.stream().map(item -> {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relation);
            return relation;
        }).collect(Collectors.toList());
        relationService.saveBatch(entities);

    }

    @Override
    public List<AttrGroupWithAttrRespVo> queryAttrGroupWithAttrByCatelogId(Long catelogId) {
        List<AttrGroupEntity> attrGroupEntities = this.baseMapper.selectList(new LambdaQueryWrapper<AttrGroupEntity>()
                .eq(AttrGroupEntity::getCatelogId, catelogId));
        List<Long> attrGroupIds = attrGroupEntities.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> relationEntities = relationService.queryRelationBy(attrGroupIds);
        List<AttrEntity> attrEntities = attrService.queryAttrByCategoryLogId(catelogId);
        List<AttrGroupWithAttrRespVo> respVos = attrGroupEntities.stream().map(item -> {
            AttrGroupWithAttrRespVo respVo = new AttrGroupWithAttrRespVo();
            BeanUtils.copyProperties(item, respVo);
            List<AttrEntity> attrs = new ArrayList<>();
            relationEntities.forEach(relationEntity -> {
                attrEntities.forEach(attrEntity -> {
                    if (Objects.equals(relationEntity.getAttrId(), attrEntity.getAttrId()
                    ) && Objects.equals(relationEntity.getAttrGroupId(), item.getAttrGroupId())) {
                        attrs.add(attrEntity);
                    }
                });
            });
            respVo.setAttrs(attrs);
            return respVo;
        }).collect(Collectors.toList());
        return respVos;
    }

    @Override
    public List<SpuItemAttrGroupVO> getAttrGroupWithAttrsBySpuId(Long spuId, Long catalogId) {
        return baseMapper.getAttrGroupWithAttrsBySpuId(spuId, catalogId);
    }

}
